
import requests
import argparse
import sys

class WeatherAPI:
    BASE_URL = "https://api.openweathermap.org/data/2.5/weather"
    
    def __init__(self, api_key):
        if not api_key:
            raise ValueError("API密钥不能为空")
        self.api_key = api_key

    def get_weather(self, city):
        params = {
            'q': city,
            'appid': self.api_key,
            'units': 'metric',
            'lang': 'zh_cn'
        }
        try:
            response = requests.get(self.BASE_URL, params=params)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as err:
            if response.status_code == 401:
                print("错误：API密钥无效，请检查密钥是否正确")
            else:
                print(f"HTTP错误: {err}")
            return None
        except Exception as e:
            print(f"请求异常: {str(e)}")
            return None

def display_weather(data, city):
    if not data:
        return False
        
    if data.get('cod') != 200:
        print(f"错误 {data.get('cod')}: {data.get('message', '未知错误')}")
        return False
        
    print(f"\n{city}天气信息:")
    print(f"温度: {data['main']['temp']}℃")
    print(f"体感温度: {data['main']['feels_like']}℃")
    print(f"湿度: {data['main']['humidity']}%")
    print(f"天气状况: {data['weather'][0]['description'].capitalize()}")
    print(f"风速: {data['wind']['speed']} m/s")
    return True

def main():
    parser = argparse.ArgumentParser(description='城市天气查询工具')
    parser.add_argument('--city', default='北京', help='指定查询城市')
    args = parser.parse_args()
    
    try:
        api = WeatherAPI("69538e7a446c8587f3ef059f250e09a2")
        data = api.get_weather(args.city)
        
        if not display_weather(data, args.city):
            sys.exit(1)
    except ValueError as e:
        print(str(e))
        sys.exit(1)

if __name__ == "__main__":
    main()
